package com.i2works.smartluolong.manage.controller.admin;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.manage.entity.admin.AdminOrgDO;
import com.i2works.smartluolong.manage.entity.admin.AdminOrgQuery;
import com.i2works.smartluolong.manage.service.admin.IAdminOrgService;
import com.i2works.smartluolong.manage.utils.BaseModule;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.base.URLConstant;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.entity.Tree;
import com.i2works.smartluolong.web.entity.common.TreeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 组织架构控制层
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/3/26 15:30
 */

@Controller
@RequestMapping("/adminOrg")
public class AdminOrgController extends BaseModule {


    private final IAdminOrgService adminOrgService;

    public AdminOrgController(IAdminOrgService adminOrgService) {
        this.adminOrgService = adminOrgService;
    }


    /**
     * 组织机构页面
     */
    @GetMapping(value = "/view/index")
    public String index() {
        logger.info("组织机构页面");
        return URLConstant.Admin.ORG_URL;
    }


    /**
     * 无分页父类资源树
     *
     * @param showStatus：0显示所有的目录（不含按钮），1显示全部分类, 2显示所有正常父类
     */
    @RequestMapping(value = "/view/tree/{showStatus:^[0-2{1}]$}")
    @ResponseBody
    public List<Tree> queryTreeList(@PathVariable Integer showStatus) {
        List<Tree> result = Lists.newArrayList();
        try {
            AdminOrgQuery query = new AdminOrgQuery();
            query.setShowStatus(showStatus);
            List<AdminOrgDO> resList = adminOrgService.queryTreeList(query);
            List<Tree> treeDataList = Lists.newArrayList();
            for (AdminOrgDO adminOrg : resList) {
                if (null != this.orgTree(adminOrg)) {
                    treeDataList.add(this.orgTree(adminOrg));
                }
            }
            result = TreeUtil.getNodeTree(0, treeDataList);
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }


    /**
     * 组织机构列表
     */
    @GetMapping(value = "/view/api")
    @ResponseBody
    public Result queryList(@ModelAttribute AdminOrgQuery query) {
        Result result = new Result();
        try {
            int total = adminOrgService.queryCount(query);
            List<AdminOrgDO> queryadminOrgList = Lists.newArrayList();
            if (total > 0) {
                queryadminOrgList = adminOrgService.queryList(query);
            }
            return R.success(queryadminOrgList, total);
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.SYSTEM_ERROR.getMsg());
        }
    }


    /**
     * 新增编辑组织机构跳转
     */
    @GetMapping(value = "/save/form")
    public String savePage() {
        logger.info("组织机构新增编辑");
        return URLConstant.Admin.ORG_FORM_URL;
    }


    /**
     * 添加组织机构
     */
    @PostMapping("/save/action")
    @ResponseBody
    public Result save(@ModelAttribute AdminOrgDO adminOrg) {
        try {
            List<Integer> keyList = Lists.newArrayList();
            if (adminOrg.getPid() == null) {
                adminOrg.setPid(0);
            }
            Integer temp = adminOrg.getPid();
            /**
             * 得到传递的父类ID，然后得到父类ID，并绑定到keyList和设置temp为父类ID
             * 把temp的父类ID当成ID，循环到上一级父类....
             */
            if (temp != 0) {
                for (; ; ) {
                    AdminOrgQuery query = new AdminOrgQuery();
                    query.setId(temp);
                    AdminOrgDO org = adminOrgService.query(query);
                    //如果PID等于0，说明上级是根路径，就不循环，如果不等于0，设置temp为PID在循环上一层
                    //复制父类ID
                    keyList.add(org.getId());
                    if (org.getPid() == 0) {
                        break;
                    } else if (org.getPid() != 0) {
                        //设置temp的ID是父类ID
                        temp = org.getPid();
                    }
                }
                //排列得到的结果
                adminOrg.setOrgKey(BaseUtils.sortListToStr(keyList));
            } else {
                //排列得到的结果
                adminOrg.setOrgKey("0");
            }
            adminOrg.setUpdateName(getUserName());
            adminOrgService.save(adminOrg);
            return R.success();
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.SAVE_ERROR.getMsg());
        }
    }

    /**
     * 查询某个资源
     */
    @GetMapping(value = "/view/{id}")
    @ResponseBody
    public Result query(@PathVariable Integer id) {
        try {
            AdminOrgQuery query = new AdminOrgQuery();
            query.setId(id);
            AdminOrgDO adminOrg = adminOrgService.query(query);
            return R.success(adminOrg);
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
    }


    /**
     * 某个系统资源（名称、标示、代码）是否存在验证
     */
    @PostMapping("/view/check")
    @ResponseBody
    public boolean queryCheck(@ModelAttribute AdminOrgQuery query) {
        try {
            int count = adminOrgService.queryCheck(query);
            return count <= 0;
        } catch (Exception e) {
            logger.error("", e);
        }
        return false;
    }

    /**
     * 更新组织状态
     */
    @PostMapping("/status/action")
    @ResponseBody
    public Result updateStatus(@ModelAttribute AdminOrgDO adminOrg) {
        Result result = new Result();
        try {
            adminOrg.setUpdateName(getUserName());
            adminOrgService.updateStatus(adminOrg);
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.STATUS_ERROR.getMsg());
        }
        return R.success();
    }

    /**
     * 更新组织状态
     * 备注：附带更新角色与组织的关联表状态
     */
    @PostMapping("/status/batchAction")
    @ResponseBody
    public Result updateBatchStatus(@RequestParam("idsList[]") List<Integer> idsList, Integer status) {
        Result result = new Result();
        try {
            if (idsList != null && idsList.size() > 0) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("idsList", idsList);
                map.put("updateName", getUserName());
                map.put("status", status);
                adminOrgService.updateBatchStatus(map);
            }
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.STATUS_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 用户下拉资源列表
     */
    @GetMapping("/view/orgSelect")
    @ResponseBody
    public Result querySelect(@ModelAttribute AdminOrgQuery query) {
        try {
            //只显示启用的
            query.setStatus(GlobalConstant.status.TRUE);
            query.setLimit(1000L);
            query.setOrgType(1);
            List<AdminOrgDO> resSelect = adminOrgService.querySelect(query);
            return R.success(resSelect, resSelect.size());
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.SYSTEM_ERROR.getMsg());
        }
    }

    /**
     * 删除
     */
    @PostMapping("/delete/action")
    @ResponseBody
    public Result delete(@RequestParam Integer id) {
        try {
            adminOrgService.delete(id);
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.DELETE_ERROR.getMsg());
        }
        return R.success();
    }

    /**
     * 批量删除
     */
    @PostMapping("/delete/batchAction")
    @ResponseBody
    public Result deleteBatch(@RequestParam("idsList[]") List<Integer> idsList) {
        try {
            if (idsList != null && idsList.size() > 0) {
                adminOrgService.deleteBatch(idsList);
            } else {
                return R.error(MsgEnum.ATTRS_EMPTY.getMsg());
            }
        } catch (Exception e) {
            logger.error("", e);
            return R.error(MsgEnum.DELETE_ERROR.getMsg());
        }
        return R.success();
    }

    /**
     * 生成过滤后的树结构
     */
    private Tree orgTree(AdminOrgDO org) throws Exception {
        Tree tree = new Tree();
        tree.setId(org.getId());
        tree.setPid(org.getPid());
        if (org.getStatus() == 0) {
            tree.setText(org.getOrgName() + "『禁』");
        } else {
            tree.setText(org.getOrgName());
        }
        tree.setType(org.getOrgType());
        tree.setSort(org.getSort());
        tree.setStatus(org.getStatus());
        tree.setUrl(org.getOrgCode());
        return tree;
    }



}
